﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.System.Area
{
    [UseDI(ServiceLifetime.Scoped)]
    public class AreaRepository : Repository<SysArea, DefaultDbContext>
    {
        private IMemoryCache memoryCache;

        public AreaRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, IMemoryCache memoryCache) : base(dbContext, applicationContext)
        {
            this.memoryCache = memoryCache;
        }

        public IEnumerable<SysArea> GetAreas()
        {
            string cacheKey = "Areas";
            var areas = memoryCache.Get<IEnumerable<SysArea>>(cacheKey);
            if (areas == null)
            {
                Sql sql = Sql.Builder.Select("*").From("sys_area");
                areas = DbContext.Fetch<SysArea>(sql);
                memoryCache.Set(cacheKey, areas, TimeSpan.FromDays(1));
            }
            return areas;
        }
    }
}